#include <stdio.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdlib.h>

int main() {
    int fd;
    int ret;
    int i2c_address = 0x48; // 假设I2C设备地址为0x91
    char buffer[256];
    int length = 10; // 假设我们要读取的数据长度为10字节
 
    // 打开I2C设备文件
    fd = open("/dev/i2c-0", O_RDWR); // 假设我们使用的是i2c-0控制器
    if (fd < 0) {
        printf("无法打开I2C设备文件\n");
        return -1;
    }
 
    // 设置I2C设备的地址
    ret = ioctl(fd, I2C_SLAVE, i2c_address);
    if (ret < 0) {
        printf("无法设置I2C设备地址\n");
        close(fd);
        return -1;
    }


    unsigned char write_buf[] = {0x1, 0x42,0x93};
    if (write(fd, write_buf, sizeof(write_buf))!= sizeof(write_buf)) {
    printf("Failed to write to the I2C device");
    return -1;
    }




    unsigned char reg = 0x0;
    int size = 0;
    // 
    if ((size = write(fd, &reg, 1)) != 1) {
	printf("I2C write  %d\n" , size);
        return -1;
    }



    // 读取数据
    ret = read(fd, buffer, length);
    if (ret < 0) {
        printf("无法读取I2C设备数据\n");
        close(fd);
        return -1;
    }
    
    printf("length %d\n", length);
    for( int i = 0; i<length; i++) {
    	printf("%d   ",buffer[i]);

    }
 
	float tmp = (buffer[0]*256 +buffer[1] ) * 0.125;
    
	printf("\n v= %f\n", tmp);
	// 处理读取的数据
    // ...
 
    close(fd); // 关闭文件
    return 0;
}
